<?php

namespace App\Http\Resources;

use App\Repositories\ProjectRepo;
use App\Repositories\TaskRepo;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;

class TaskResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $projectPercentResidue = ProjectRepo::taskPercentResidue($this->project);
        $taskPercentResidue = $projectPercentResidue;

        $currentUserId = registry('user_id') ?? 0;
        $project = $this->project;
        $projectUserId = $project->user_id ?? 0;

        $isProjectUser = false;
        if ($projectUserId == $currentUserId || $currentUserId == 1) {
            $isProjectUser = true;
        }

        $isTaskUser = false;
        $userIds = $this->users->pluck('user_id')->toArray();
        $userIds[] = 1;
        if (in_array($currentUserId, $userIds)) {
            $isTaskUser = true;
        }

        return [
            'id' => $this->id,
            'type' => $this->type,
            'plan_work_hour' => $this->plan_work_hour,
            'plan_product_quantity' => $this->plan_product_quantity,
            'work_hour' => $this->work_hour,
            'name' => $this->name ?: $this->type ?: '',
            'task_number' => $this->task_number,
            'percent' => $this->percent,
            'percent_format' => $this->percent_format,
            'users' => $this->getUsers(),
            'product_count' => $this->products->count(),
            'start_at' => $this->start_at,
            'complete_at' => $this->complete_at,
            'plan_start_at' => $this->plan_start_at,
            'plan_complete_at' => $this->plan_complete_at,
            'status' => $this->status,
            'status_text' => $this->status_text,
            'project_id' => $this->project_id,
            'project_name' => $this->project->name ?? '',
            'project_number' => $this->project->project_number ?? '',
            'schedule' => $this->schedule,
            'schedule_text' => $this->schedule_text,
            'create_at' => Carbon::parse($this->create_time)->toDateTimeString(),
            'description' => $this->description,
            'logs' => $this->getLogs(),
            'plan' => $this->getPlans(),
            'histories' => $this->histories(),
            'percent_residue' => $taskPercentResidue,
            'is_project_user' => $isProjectUser,
            'is_task_user' => $isTaskUser,
            'project_status' => $this->project->status ?? '',
            'project_status_text' => $this->project->status_text ?? ''
        ];
    }

    private function getLogs()
    {
        $histories = $this->histories;
        if (!$histories->count()) {
            return [];
        }
        $logs = [];
        foreach ($histories as $history) {
            $logs[] = [
                'id' => $history->id,
                'user_name' => $history->user->realname ?? '',
                'create_time' => Carbon::parse($history->create_time)->toDateTimeString(),
                'action' => TaskRepo::getActionContentByStatus($history->status)
            ];
        }
        return $logs;
    }

    private function getUsers()
    {
        $users = $this->users;
        if (!$users->count()) {
            return [];
        }
        $result = [];
        foreach ($users as $user) {
            $result[] = [
                'id' => $user->user_id,
                'name' => $user->user->realname ?? ''
            ];
        }
        return $result;
    }

    private function histories()
    {
        $histories = $this->histories;
        if (!$histories->count()) {
            return [];
        }
        $results = [];
        $histories = $histories->toArray();
        foreach ($histories as $history) {
            $status = $history['status'];
            $userName = $history['user']['realname'] ?? '';
            $itemResult = '';
            switch ($status) {
                case TaskRepo::STATUS_CLOSED:
                    $itemResult = "{$userName}关闭了任务";
                    break;
                case TaskRepo::STATUS_COMPLETED:
                    $itemResult = "{$userName}完成了任务";
                    break;
                case TaskRepo::STATUS_STARTED:
                    $itemResult = "{$userName}开始了任务";
                    break;
                case TaskRepo::STATUS_PAUSED:
                    $itemResult = "{$userName}暂停了任务";
                    break;
                case TaskRepo::STATUS_UN_START:
                    $itemResult = "{$userName}创建了任务";
                    break;
            }
            $results[] = [
                'message' => $itemResult,
                'date' => Carbon::parse($history['create_time'])->toDateTimeString()
            ];
        }
        return $results;
    }

    private function getPlans()
    {
        return [
            'plan_start_at' => $this->plan_start_at,
            'plan_complete_at' => $this->plan_complete_at,
            'start_at' => $this->start_at,
            'complete_at' => $this->complete_at,
            'plan_work_hour' => $this->plan_work_hour,
            'work_hour' => $this->work_hour,
        ];
    }
}
